//
//  HTTPManager.m
//  MiBaoTu
//
//  Created by admin on 16/9/20.
//  Copyright © 2016年 com.caesartech15. All rights reserved.
//

#import "HTTPManager.h"
#import "UpdateProgressView.h"
#import "AFNetworking.h"

@interface HTTPManager ()<NSURLSessionDelegate>

@property (nonatomic,strong)UIView      *selectView;
@property (nonatomic,strong)UpdateProgressView          *updateView;

@end
@implementation HTTPManager

+ (HTTPManager *)standerDefault
{
    static HTTPManager *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [HTTPManager new];
    });
    return manager;
}

- (void)AFGetRequest:(NSString *)urlPath view:(UIView *)view success:(Success)success failure:(Failure)failure
{
    NSString *pathStr = urlPath;
    NSDictionary* infoDict =[[NSBundle mainBundle] infoDictionary];
    NSString* versionName =[infoDict objectForKey:@"CFBundleVersion"];
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.requestSerializer.timeoutInterval = 6;
    [manager.requestSerializer setValue:@"IOS" forHTTPHeaderField:@"Client"];
    [manager.requestSerializer setValue:[UIDevice currentDevice].systemVersion forHTTPHeaderField:@"Os"];
    [manager.requestSerializer setValue:[UIDevice currentDevice].model forHTTPHeaderField:@"Model"];
    //    [httpClient.requestSerializer setValue:ChannelName forHTTPHeaderField:@"Channel"];
    [manager.requestSerializer setValue:@"2980" forHTTPHeaderField:@"Version-Code"];
    [manager.requestSerializer setValue:versionName forHTTPHeaderField:@"Version-Name"];
    [manager.requestSerializer setValue:[UIDevice currentDevice].identifierForVendor.UUIDString forHTTPHeaderField:@"IMEI"];
    //    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", nil];
    [manager GET:pathStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (view) {
            //            [hud hide:YES];
            //            [_myView stopAnimating];
        }
        NSDictionary *dic = (NSDictionary *)responseObject;
        
        if (success) {
            
            success(dic);
            
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:view animated:YES];
        if (failure) {
            if (view) {
                //                [hud hide:YES];
                //                [_myView stopAnimating];
            }
            failure(error);
        }
        
    }];
    
}
- (void)AFPostRequest:(NSString *)urlPath view:(UIView *)view parameters:(NSDictionary *)parameters success:(Success)success failure:(Failure)failure
{
    NSString *pathStr = urlPath;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    //    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager.requestSerializer setValue:@"Content-type" forHTTPHeaderField:@":image/png"];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"application/json"];
    [manager POST:pathStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = (NSDictionary *)responseObject;
        if (view) {
            //            [hud hide:YES];
            //            [_myView stopAnimating];
        }
        if (success) {
            success(dic);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (view) {
            //            [hud hide:YES];
            //            [_myView stopAnimating];
        }
        if (failure) {
            failure(error);
        }
        
    }];
}

- (void)setOrientation:(UIDeviceOrientation)orientation
{
    _orientation = orientation;
    if (_updateView) {
        _updateView.orientation = orientation;
    }
}

- (void)onUpdateMusicWithView:(UIView *)view;
{
    self.selectView = view;
    _updateView = [[UpdateProgressView alloc]init];
    _updateView.orientation = self.orientation;
    [_updateView showInView:view];
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:[[NSOperationQueue alloc]init]];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"http://120.25.226.186:32812/upload"]];
    request.timeoutInterval = 30;
    [request setHTTPMethod:@"POST"];
    [request setValue:[NSString stringWithFormat:@"multipart/form-data;boundary=%@",@"----WebKitFormBoundary0IQAt0HA7oxwIx3f"] forHTTPHeaderField:@"Content-Type"];
    
    NSURLSessionUploadTask *upLoadTask = [session uploadTaskWithRequest:request
                                                               fromData:[self getBodyData]
                                                      completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@",[[NSString alloc]initWithData:data encoding:NSUTF8StringEncoding]);
                                                          if (self.UpdateMusicSendFinishBlock) {
                                                              self.UpdateMusicSendFinishBlock(data,response,error);
                                                          }
    }];
    [upLoadTask resume];
}

#define kBoundary @"----WebKitFormBoundary0IQAt0HA7oxwIx3f"
#define KNewLine [@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]
-(NSData *)getBodyData
{
    //5.拼接数据
     NSMutableData *fileData = [NSMutableData data];

   //5.1 拼接文件参数
   /*
     --分隔符
    Content-Disposition: form-data; name="file"; filename="Snip20151228_572.png"
    Content-Type: image/png
    空行
    文件二进制数据
    */
     [fileData appendData:[[NSString stringWithFormat:@"--%@",kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
     [fileData appendData:KNewLine];
     // name="file":参数,是固定的
     // filename:文件上传到服务器以什么名字来保存,随便
     [fileData appendData:[@"Content-Disposition: form-data; name=\"file\"; filename=\"Snip20151228_572.png\"" dataUsingEncoding:NSUTF8StringEncoding]];

     [fileData appendData:KNewLine];
     //Content-Type:要上传的文件的类型 (MIMEType)
     [fileData appendData: [@"Content-Type: image/png" dataUsingEncoding:NSUTF8StringEncoding]];
     [fileData appendData:KNewLine];
     [fileData appendData:KNewLine];

     UIImage *image = [UIImage imageNamed:@"bg_qzxbf"];
     NSData *imageData = UIImagePNGRepresentation(image);
     [fileData appendData:imageData];
     [fileData appendData:KNewLine];

     //5.2 拼接非文件参数
     /*
      --分隔符
      Content-Disposition: form-data; name="username"
      空行
      非文件参数的二进制数据
      */
     [fileData appendData:[[NSString stringWithFormat:@"--%@",kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];
     [fileData appendData:KNewLine];

     //username:同file 是服务器规定
     [fileData appendData:[@"Content-Disposition: form-data; name=\"username\"" dataUsingEncoding:NSUTF8StringEncoding]];
     [fileData appendData:KNewLine];
    [fileData appendData:KNewLine];
    [fileData appendData:[@"dashen9" dataUsingEncoding:NSUTF8StringEncoding]];
    [fileData appendData:KNewLine];

    //5.3 拼接结尾标识
    /*
     --分隔符--
     */
     [fileData appendData:[[NSString stringWithFormat:@"--%@--",kBoundary] dataUsingEncoding:NSUTF8StringEncoding]];

     return fileData;
}

- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
   didSendBodyData:(int64_t)bytesSent
    totalBytesSent:(int64_t)totalBytesSent
totalBytesExpectedToSend:(int64_t)totalBytesExpectedToSend
{
//    NSLog(@"已经上传了%f的数据",1.0 * totalBytesSent/totalBytesExpectedToSend );
    float update = 100.00 * totalBytesSent/totalBytesExpectedToSend;
    if (self.UpdateMusicSendDataBlock) {
        self.UpdateMusicSendDataBlock((int)update);
        
    }
    
    _updateView.progress = (int) update;
}

@end
